//todo vue的懒加载

export default class LazyLoadImg {
  constructor(opts) {
    let _loop = function() {};
    this.tag = 'data-src';
    this.distance = 0;
    this.callback = _loop;
    this.oScroll = window;
    this.gloabl = {};
    // debugger
    this._init(opts);
  }

  _init(opts) {
    //minxin
    var _self = this;
    let optss = opts || {};
    for (let key in optss) {
      this[key] = optss[key];
    }
    this.gloabl.W = window.innerWidth || document.documentElement.clientWidth;
    this.gloabl.H = window.innerHeight || document.documentElement.clientHeight;
    this.oScroll = typeof this.oScroll === "string" ? document.querySelector(
      this.oScroll) : elements || window;
    this.elements = typeof this.elements === "string" ? Array.from(this.oScroll
      .querySelectorAll(this.elements)) : elements;

    this._detectElementIfInScreen(null, this);
    //添加事件
    this.oScroll.addEventListener('scroll', function(e) {
      _self._detectElementIfInScreen(e, _self);
    }, false);
  }

  _loadItem(ele) {
    let _src = ele.getAttribute(this.tag);
    if (_src) {
      ele.setAttribute("src", _src);
    }
  }
  _detectElementIfInScreen(e, self) {
    // console.log(1);
    if (!self.elements.length) return;

    for (let i = 0, len = this.elements.length; i < len; i++) {
      let ele = self.elements[i];
      let rect = ele.getBoundingClientRect();
      if (!self._pause && (rect.top >= self.distance && rect.left >= self.distance ||
          rect.top < 0 && (rect.top + rect.height) >= self.distance || rect.left <
          0 && (rect.left + rect.width >= self.distance)) && rect.top <= this
        .gloabl.H && rect.left <= self.gloabl.W) {
        self._loadItem(ele);
        // debugger
        self.elements.splice(i, 1);
        i--;
        len--;
      }
    }

    if (!self.elements.length) {
      this.callback && self.callback();
    }
  }
}
